import { Link } from 'react-router-dom'
import { useAppSelector } from '../../../../store/hooks'
import {
	selectAllProducts,
	selectUser,
} from '../../../../store/reducers/selectors'
import { useEffect, useState } from 'react'
import Favorites from '../../../../assets/favorites.svg'
import { Badge } from '@mui/material'
import { withLoading } from '../../../../hoc/withLoading'

const FavoritesButton = withLoading(() => {
	const user = useAppSelector(selectUser)
	const allProducts = useAppSelector(selectAllProducts)
	const [favorites, setFavorites] = useState(0)

	useEffect(() => {
		if (!user) return
		const count =
			allProducts?.filter((item) => item.likes.includes(user?._id)).length || 0
		setFavorites(count)
	}, [allProducts, user])

	return (
		<Link to={'favorites'}>
			<Badge badgeContent={favorites}>
				<Favorites />
			</Badge>
		</Link>
	)
})

export default FavoritesButton
